package com.ambitor.ipro.app.sche;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.ipro.exceptions.ProException;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.PropertiesReader;
import com.ambitor.ipro.util.PropertiesReaderForPic;
import com.ambitor.ipro.util.ResultCode;
import com.ambitor.ipro.util.Utils;
import com.taobao.api.domain.Item;

public class InstallerHelper {

	private TopService topService = null;

	private SuperDao superDao = null;

	private IData userSession = null;

	private IData userPro = null;

	private IData userStyle = null;

	private String installIid = null;

	private String shopURL = "#";

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	public InstallerHelper(SuperDao superDao, TopService topService,
			IData userSession, IData userPro, IData userStyle, String shopURL) {
		this.superDao = superDao;
		this.topService = topService;
		this.userSession = userSession;
		this.userStyle = userStyle;
		this.userPro = userPro;
		this.shopURL = shopURL;
	}

	public void setInstallIid(String installIid) {
		this.installIid = installIid;
	}

	public String builderProHTML(List<Item> staticItemList,
			List<Item> intellItemList) throws ProException {
		List<Item> allItemListToBePromoted = buildAllItemsToBePromoted(
				staticItemList, intellItemList);
		String proModuleHTML = buildPromHTML(allItemListToBePromoted);
		return proModuleHTML;
	}

	public String installInTaobao(String promotionModule) throws ProException {
		String nick = userSession.getString("NICK");
		String sessionId = userSession.getString("SESSION_ID");

		Long installNumIid = Long.valueOf(installIid);
		String installType = userPro.getString("INSTALL_TYPE");
		return topService.intallPromotionModule(sessionId, nick, installNumIid,
				installType, promotionModule);
	}

	private List<Item> buildAllItemsToBePromoted(List<Item> staticItemList,
			List<Item> intellItemList) {
		int staticNum = userPro.getInt("STATIC_NUM");
		int intellNum = userPro.getInt("INTELL_NUM");

		List<Item> filtedStaticItemList = new ArrayList<Item>();
		for (Item staticItem : staticItemList) {
			if (!installIid.equals(staticItem.getNumIid().toString())) {
				filtedStaticItemList.add(staticItem);
			}
		}

		List<Item> filtedIntellItemList = new ArrayList<Item>();
		int minus = intellNum + staticNum - filtedStaticItemList.size();
		int i = 0;
		for (Item intellItem : intellItemList) {
			if (i == minus)
				break;
			boolean isExists = false;
			if (installIid.equals(intellItem.getNumIid().toString())) {
				isExists = true;
			} else {
				for (Item staticItem : filtedStaticItemList) {
					if (intellItem.getNumIid().equals(staticItem.getNumIid())) {
						isExists = true;
						break;
					}
				}
			}
			if (isExists == false) {
				filtedIntellItemList.add(intellItem);
				i++;
			}
		}

		List<Item> allItemListToBePromoted = new ArrayList<Item>();
		String intellFirst = userStyle.getString("INTELL_FIRST_FLAG",
				Constants.FLAG_YES);
		if (Constants.FLAG_YES.equals(intellFirst)) {
			allItemListToBePromoted.addAll(filtedIntellItemList);
			allItemListToBePromoted.addAll(filtedStaticItemList);
		} else {
			allItemListToBePromoted.addAll(filtedIntellItemList);
			allItemListToBePromoted.addAll(filtedStaticItemList);
		}

		return allItemListToBePromoted;
	}


	@SuppressWarnings("unchecked")
	public String buildPromHTML(List<Item> allItemListToBePromoted)
			throws ProException {
		String sStyleId = userStyle.getString("STANDARD_STYLE");
		IData param = new DataMap();
		param.put("SSTYLE_ID", sStyleId);
		IData sstyleMap = null;
		try {
			sstyleMap = superDao.queryByPK("TD_P_SSTYLE", param);
		} catch (Exception e) {
			throw new ProException(ResultCode.DB_EXCEPTION, "查询TD_P_SSTYLE出错",
					e);
		}

		int moduleId = sstyleMap.getInt("MODULE_ID");
		param.clear();
		param.put("MODULE_ID", moduleId);

		IData moduleMap = null;
		try {
			moduleMap = superDao.queryByPK("TD_P_MODULE", param);
		} catch (Exception e) {
			throw new ProException(ResultCode.DB_EXCEPTION, "查询TD_P_MODULE出错",
					e);
		}

		String proModuleTemplate = moduleMap.getString("IPRO_MODULE_CODE");

		// 替换search code
		String searchCode = buildSearchCode(moduleMap);
		proModuleTemplate = proModuleTemplate.replace("#{search_code}",
				searchCode);

		// 替换收藏店铺
		String favShopCode = StringUtils.EMPTY;
		if (Constants.FLAG_YES.equals(userStyle.getString("IS_FAV"))) {
			favShopCode = moduleMap.getString("FAV_SHOP_CODE");
		}
		proModuleTemplate = proModuleTemplate.replace("#{fav_shop_code}",
				favShopCode);

		// 替换旺旺
		String wangwangCode = StringUtils.EMPTY;
		if (Constants.FLAG_YES.equals(userStyle.getString("IS_WANGWANG"))) {
			wangwangCode = moduleMap.getString("WANGWANG_CODE");
		}
		proModuleTemplate = proModuleTemplate.replace("#{wangwang_code}",
				wangwangCode);

		// 替换pro_content
		String proContent = buildCode4AllItems(allItemListToBePromoted,
				moduleMap);
		proModuleTemplate = proModuleTemplate.replace("#{pro_content}",
				proContent);

		// 替换其它所有的@{}变量
		return replaceAllGloableVariables(moduleMap, sstyleMap,
				proModuleTemplate);
	}

	private String buildSearchCode(IData moduleMap) {
		String keyWords = userStyle.getString("KEY_WORDS");
		if (StringUtils.isBlank(keyWords)) {
			return StringUtils.EMPTY;
		}
		String[] keyWordsArray = keyWords.split(",");
		String SingleSearchCode = moduleMap.getString("SEARCH_CODE");
		StringBuilder sb = new StringBuilder("");
		String seperator = "┊ ";
		int i = 0;
		for (String keyWord : keyWordsArray) {
			if (++i > 5) // 最多5个关键字
				break;
			String singleCode = StringUtils.replace(SingleSearchCode,
					"@{key_word}", keyWord);
			String encodeKeyWord = keyWord;
			try {
				encodeKeyWord = URLEncoder.encode(keyWord, "GBK");
			} catch (UnsupportedEncodingException e) {
			}
			singleCode = StringUtils.replace(singleCode, "@{encode_key_word}",
					encodeKeyWord);
			sb.append(singleCode);
			if (i < keyWordsArray.length)
				sb.append(seperator);
		}
		return sb.toString();
	}

	private String buildCode4AllItems(List<Item> allItemListToBePromoted,
			IData moduleMap) {
		StringBuilder prModuleHTML4AllItems = new StringBuilder("");
		String trCode = moduleMap.getString("ITEM_TR_CODE");
		String tdCode = moduleMap.getString("ITEM_TD_CODE");
		int numPerLine = userStyle.getInt("NUM_PER_LINE");
		for (int i = 0; i < allItemListToBePromoted.size(); i++) {
			Item itemToBePromoted = allItemListToBePromoted.get(i);
			if (i % numPerLine == 0) {
				prModuleHTML4AllItems.append(trCode); // 新一行推广位
			}
			prModuleHTML4AllItems.append(tdCode);
			String proModuleHTML4OneItem = buildProModule4OneItem(
					itemToBePromoted, moduleMap);
			prModuleHTML4AllItems.append(proModuleHTML4OneItem);
			prModuleHTML4AllItems.append("</td>");

			if ((i + 1) % numPerLine == 0
					|| i == allItemListToBePromoted.size() - 1) {
				prModuleHTML4AllItems.append("</tr>");// 一行推广位的结束
			}
		}
		return prModuleHTML4AllItems.toString();
	}

	private String buildProModule4OneItem(Item itemToBePromoted, IData moduleMap) {
		String proModuleHTML4OneItem = moduleMap.getString("ITEM_MODULE_CODE");
		String itemContentCode = buildItemContentCode(itemToBePromoted,
				moduleMap);
		proModuleHTML4OneItem = proModuleHTML4OneItem.replace(
				"#{item_content_code}", itemContentCode);
		return proModuleHTML4OneItem;
	}

	private String buildItemContentCode(Item itemToBePromoted, IData moduleMap) {
		StringBuilder itemContentCode = new StringBuilder();
		// append图片html
		String itemPicCode = moduleMap.getString("ITEM_PIC_CODE");
		String isPromotionLable = userStyle.getString("IS_PROMOTION_LABEL");
		// String promotionLableCode = StringUtils.EMPTY;
		String promotionLableCode = "<div style=\"width:@{td_height};height:@{td_width}; cursor:hand;\"></div>";
		if (Constants.FLAG_YES.equals(isPromotionLable)) {
			promotionLableCode = moduleMap.getString("ITEM_PROM_LABEL_CODE");
		}
		itemPicCode = itemPicCode.replace("#{promotion_label_code}",
				promotionLableCode);
		itemContentCode.append(itemPicCode);

		// append title/price_label/buy_button的html
		String layout = userStyle.getString("LAYOUT");
		if (StringUtils.isNotBlank(layout)) {
			String[] elementArray = layout.split(",");
			for (String element : elementArray) {
				if ("item_price_code".equalsIgnoreCase(element)) {
					String priceStyle = userStyle.getString("PRICE_STYLE");
					String priceCode = moduleMap.getString("ITEM_PRICE_CODE_"
							+ priceStyle);
					itemContentCode.append(priceCode);
				} else {
					String elmentCode = moduleMap.getString(element
							.toUpperCase());
					itemContentCode.append(elmentCode);
				}
			}
		}

		// append已SaleoutNum Html
		String isSaleNum = userStyle.getString("IS_SALE_NUM");
		if (Constants.FLAG_YES.equals(isSaleNum)) {
			String saleText = userStyle.getString("SALE_TEXT");
			String saleOutCode = moduleMap.getString("ITEM_SALE_OUT_CODE");
			saleOutCode = saleOutCode.replace("@{sale_text}", saleText);
			String saleNum = getSaleNum(itemToBePromoted);
			saleOutCode = saleOutCode.replace("@{sale_num}", saleNum);
			itemContentCode.append(saleOutCode);
		}
		return replaceItemVariables(itemToBePromoted, itemContentCode
				.toString());
	}

	private String replaceItemVariables(Item itemToBePromoted,
			String itemContentCode) {
		// 宝贝IID
		itemContentCode = itemContentCode.replace(Constants.IID_IN_STYLE_CODE,
				itemToBePromoted.getNumIid().toString());

		// 替换宝贝图片地址
		String picUrl = itemToBePromoted.getPicUrl();
		if (!picUrl.endsWith("intell.jpg")) {
			int numPerLine = userStyle.getInt("NUM_PER_LINE");
			String picSuffix = PropertiesReader.getString("TAOBAO_PIC_"
					+ numPerLine);
			picUrl += picSuffix;
		}
		itemContentCode = itemContentCode.replace(
				Constants.PIC_URL_IN_STYLE_CODE, picUrl);

		// 替换宝贝名称
		String itemTitle = itemToBePromoted.getTitle();
		if (itemTitle.length() > Constants.TITLE_LENGTH_TO_TRIM) {
			itemTitle = itemTitle.substring(0, 18) + "··";
		}
		itemContentCode = itemContentCode.replace(
				Constants.ITEM_TITLE_IN_STYLE_CODE, itemTitle);

		// 替换价格
		String price = itemToBePromoted.getPrice();
		itemContentCode = itemContentCode.replace(
				Constants.PRICE_IN_STYLE_CODE, price);

		// 替换市场价
		String priceStyle = userStyle.getString("PRICE_STYLE");
		double PriceDouble = Double.parseDouble(price);
		int marketPriceMultiple = userStyle.getInt("MARKET_PRICE");// 市场价倍数
		String marketPrice = (PriceDouble * marketPriceMultiple / 100) + "";
		if ("2".equals(priceStyle)) {
			itemContentCode = itemContentCode.replace("@{market_price}",
					marketPrice);
		}

		return itemContentCode;
	}

	// TODO
	private String getSaleNum(Item item) {
		return "0";
	}

	private String replaceAllGloableVariables(IData moduleMap, IData sstyleMap,
			String proModuleTemplate) {
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				Constants.SHOP_URL_IN_STYLE_CODE, shopURL);

		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				Constants.FROM_IID_IN_STYLE_CODE, installIid);

		String title = userStyle.getString("TITLE");
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				Constants.TITLE_IN_STYLE_CODE, title);

		proModuleTemplate = StringUtils.replace(proModuleTemplate, "@{color}",
				sstyleMap.getString("COLOR"));

		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{sale_text}", userStyle.getString("SALE_TEXT"));

		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{buy_now_button}", PropertiesReaderForPic.getString(userStyle
						.getString("BUY_BUTTON")));

		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{price_label}", PropertiesReaderForPic.getString(userStyle
						.getString("PRICE_LABEL")));

		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{promotion_label}", PropertiesReaderForPic
						.getString(userStyle.getString("PROMOTION_LABEL")));

		// 替换价格名称
		String marketPriceName = StringUtils.EMPTY;
		String realPriceName = StringUtils.EMPTY;
		String priceText = userStyle.getString("PRICE_TEXT");
		String priceStyle = userStyle.getString("PRICE_STYLE");
		if ("2".equals(priceStyle)) {
			if (StringUtils.isNotBlank(priceText)) {
				marketPriceName = priceText.split(",")[0].trim() + ":";
				realPriceName = priceText.split(",")[1].trim() + ":";
			}
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{market_price_name}", marketPriceName);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{real_price_name}", realPriceName);

		// 替换旺旺号码
		String wangwang = userStyle.getString("WANGWANG");
		try {
			if (StringUtils.isNotBlank(wangwang)) {
				wangwang = URLEncoder.encode(wangwang, "GBK");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{encode_wangwang}", wangwang);

		// 原价是否要加划线
		String strikeStart = StringUtils.EMPTY;
		String strikeEnd = StringUtils.EMPTY;
		if (Constants.FLAG_YES.equals(userStyle.getString("IS_PRICE"))
				&& "2".equals(userStyle.getString("PRICE_STYLE"))
				&& Constants.FLAG_YES.equals(userStyle
						.getString("IS_PRICE_STRIKE"))) {
			strikeStart = "<strike>";
			strikeEnd = "</strike>";
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{strike_start}", strikeStart);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{strike_end}", strikeEnd);

		// 替换table_id
		String installPlace = "top";
		if (userPro != null && userPro.size() > 0) {
			installPlace = userPro.getString("INSTALL_PLACE");
		}
		proModuleTemplate = proModuleTemplate.replace("@{ipromotion_id}",
				PropertiesReader.getString("IPROMOTION_ID_"
						+ installPlace.toUpperCase()));

		// 替换背景图片
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{head_bg_pic}", sstyleMap.getString("HEAD_BG_PIC"));
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{tail_bg_pic}", sstyleMap.getString("TAIL_BG_PIC"));

		// 替换收藏店铺地址
		String addFavUrl = StringUtils.EMPTY;
		if (Constants.FLAG_YES.equals(userStyle.getString("IS_FAV"))) {
			addFavUrl = userSession.getString("ADD_FAV_URL");
			if (StringUtils.isBlank(addFavUrl)) {
				try {
					addFavUrl = topService.getFavUrl(shopURL);
				} catch (Exception e) {
					logger.warn(userSession.getString("NICK") + "获取店铺地址时发生错误");
				}
			} else {
			}
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{add_fav_url}", addFavUrl);

		// 替换marquee
		String staticFlag = userStyle.getString("STATIC_FLAG");
		String marqueeStart = StringUtils.EMPTY;
		String marqueeEnd = StringUtils.EMPTY;
		String spacingLength = "11";
		String contentTableLength = "745";
		if (Constants.FLAG_NO.equals(staticFlag)) {
			marqueeStart = moduleMap.getString("MARQUEE_START_CODE");
			marqueeEnd = "</marquee>";
			spacingLength = "8";
			contentTableLength = "735";
		}
		proModuleTemplate = proModuleTemplate.replace("#{marquee_start}",
				marqueeStart);
		proModuleTemplate = proModuleTemplate.replace("#{marquee_end}",
				marqueeEnd);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{spacing_length}", spacingLength);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{content_table_length}", contentTableLength);

		// 替换item_td的高和宽度
		int numPerLine = userStyle.getInt("NUM_PER_LINE");
		String size = "170px";
		if (numPerLine == 5) {
			size = "130px";
		}
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{td_height}", size);
		proModuleTemplate = StringUtils.replace(proModuleTemplate,
				"@{td_width}", size);

		String pro4Ipro = userStyle.getString("PRO4IPRO");
		String proText = Utils.getProModuleNoticeText(pro4Ipro);
		proModuleTemplate = proModuleTemplate.replace("@{pro4ipro}", proText);

		return proModuleTemplate;
	}
}
